package com.sly.fuxi.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author SLY
 * @date 2025/2/10
 */
@Configuration
public class ThreadPoolConfig {

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(5);
        // 最大线程数
        executor.setMaxPoolSize(10);
        // 队列容量
        executor.setQueueCapacity(20);
        // 线程空闲时间
        executor.setKeepAliveSeconds(60);
        // 线程名称前缀
        executor.setThreadNamePrefix("TaskPool-");
        // 任务拒绝策略
        executor.setRejectedExecutionHandler((r, e) -> System.out.println("任务被拒绝: " + r.toString()));
        executor.initialize();
        return executor;
    }

    @Bean("taskWaitingExecutor")
    public Executor taskWaitingExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(2);
        // 最大线程数
        executor.setMaxPoolSize(4);
        // 队列容量
        executor.setQueueCapacity(10);
        // 线程空闲时间
        executor.setKeepAliveSeconds(60);
        // 线程名称前缀
        executor.setThreadNamePrefix("WaitingPool-");
        // 自定义任务拒绝策略
        executor.initialize();
        executor.setRejectedExecutionHandler(new WaitingRejectedExecutionHandler());
        return executor;
    }
}
